package com.abe.mvp.view.activity;

import java.util.ArrayList;
import java.util.List;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;

import com.abe.config.Constants;
import com.abe.mvp.model.bean.CardMenuBean;
import com.abe.mvp.view.activity.base.BaseActivity;
import com.abe.mvp.view.adapter.CardMenuAdapter;
import com.abe.strengthtrainer.R;

@ContentView(R.layout.activity_setting_apps)
public class AppsActivity extends BaseActivity implements OnItemClickListener {

	@ViewInject(R.id.show_exercise_button_back)
	private LinearLayout show_exercise_button_back;

	@ViewInject(R.id.setting_launcher_grid)
	private GridView setting_launcher_grid;
	private List<CardMenuBean> appBeans;
	private List<ResolveInfo> mApps;
	private CardMenuAdapter appAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initView();
	}

	private void initView() {
		show_exercise_button_back.setVisibility(View.VISIBLE);
		appBeans = new ArrayList<CardMenuBean>();
		mApps = Constants.loadApps();
		for (int i = 0; i < mApps.size(); i++) {
			CardMenuBean bean = new CardMenuBean();
			ResolveInfo resolveInfo = mApps.get(i);
			bean.setName(resolveInfo.activityInfo
					.loadLabel(getPackageManager()).toString());
			bean.setDrawable(resolveInfo.activityInfo
					.loadIcon(getPackageManager()));
			bean.setType(Drawable.class);
			appBeans.add(bean);
		}
		appAdapter = new CardMenuAdapter(this, appBeans, scale);
		setting_launcher_grid.setAdapter(appAdapter);
		setting_launcher_grid.setOnItemClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
		ResolveInfo info = mApps.get(pos);
		/** 该应用的包名 */
		String pkg = info.activityInfo.packageName;
		/** 应用的主activity类 */
		String cls = info.activityInfo.name;
		ComponentName componet = new ComponentName(pkg, cls);
		Intent i = new Intent();
		i.setComponent(componet);
		startActivity(i);
	}

	@Event(value = R.id.show_exercise_button_back, type = View.OnClickListener.class)
	private void back(View view) {
		back();
	}
}
